<template>
    <div class="file-uploader">
        <div class="upload-section">
            <UpLoadFile 
                v-model="uploadedFiles"
                label="导入文件"
                placeholder="点击导入文件"
                :multiple="true"
                :maxCount="1"
                :maxSize="10 * 1024 * 1024"
                :accept="'.xlsx, .xls'"
                @error="handleError"
            />
            <div class="template-download">
                <van-button 
                    type="primary" 
                    size="small" 
                    icon="download" 
                    @click="downloadTemplate"
                    class="download-btn"
                >
                    下载模板
                </van-button>
                
            </div>
            <div class="">
                <p>苹果用户如果无法下载,请复制url,在Safari浏览器下载</p>
                <a :href="`${windowLocationOrigin}/template/import_template.xlsx`" target="_blank" class="download-link">{{windowLocationOrigin}}/template/import_template.xlsx</a>
            </div>
        </div>

        <!-- 上传文件列表 -->
        <div class="upload-list" v-if="uploadedFiles.length > 0">
            <div class="list-header">
                <h3>上传文件列表</h3>
                <div class="header-actions">
                    <van-button size="small" type="danger" @click="clearUploadedFiles">清空</van-button>
                </div>
            </div>
            <div class="list-content">
                <table class="file-table">
                    <thead>
                        <tr>
                            <th class="th-info">文件信息</th>
                            <th class="th-status">状态</th>
                            <th class="th-actions">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(file, index) in uploadedFiles" :key="index" class="file-row">
                            <td class="td-info">
                                <div class="file-name" :title="file.name">{{ file.name }}</div>
                                <div class="file-meta">
                                    <span class="serial-number">{{ index + 1 }}</span>
                                    <span class="file-size">{{ formatFileSize(file.size) }}</span>
                                </div>
                            </td>
                            <td class="td-status">
                                <template v-if="file.status === 'uploading'">
                                    <van-loading type="spinner" size="16" />
                                    <span>上传中...</span>
                                </template>
                                <template v-else-if="file.status === 'failed'">
                                    <van-icon name="cross" color="#ee0a24" />
                                    <span>上传失败</span>
                                </template>
                                <template v-else>
                                    <van-icon name="success" color="#07c160" />
                                    <span>上传成功</span>
                                </template>
                            </td>
                            <td class="td-actions">
                                <van-icon name="delete" @click="removeUploadedFile(file)" class="action-icon" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 使用日志列表组件 -->
        <LogList 
            ref="logListRef"
            :initialPageSize="pageSize"
        />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { 
    Icon as VanIcon, 
    Button as VanButton,
    Loading as VanLoading,
    showToast
} from 'vant';
import request from '@/utils/request';
import apiUrls from '@/config/apiUrls'; 
import UpLoadFile from '@/Pages/compontents/UpLoadFile.vue';
import LogList from './LogList.vue';

const logListRef = ref(null);
const pageSize = ref(20);

const windowLocationOrigin = ref(window.location.origin);

// 上传文件相关
const uploadedFiles = ref([]);

// 处理上传错误
const handleError = (error) => {
    console.error('上传错误:', error);
    showToast(error.message || '上传失败，请重试');
};

// 下载模板文件
const downloadTemplate = () => {
    try {
        // 直接使用本地模板文件
        const templateUrl = '/template/import_template.xlsx';
        
        // 创建一个隐藏的a标签用于下载
        const link = document.createElement('a');
        link.href = templateUrl;
        link.setAttribute('download', '导入模板.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showToast({
            message: '模板下载成功',
            type: 'success'
        });
    } catch (error) {
        console.error('模板下载失败:', error);
        showToast({
            message: '模板下载失败，请重试',
            type: 'fail'
        });
    }
};

// 上传文件相关方法
const removeUploadedFile = (file) => {
    const index = uploadedFiles.value.indexOf(file);
    if (index !== -1) {
        uploadedFiles.value.splice(index, 1);
    }
};

const clearUploadedFiles = () => {
    uploadedFiles.value = [];
};

// 通用方法
const formatFileSize = (size) => {
    if (!size) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;
    while (size >= 1024 && index < units.length - 1) {
        size /= 1024;
        index++;
    }
    return `${size.toFixed(2)} ${units[index]}`;
};

onMounted(() => {
    // 不需要在这里调用refreshLogList，因为LogList组件会自己调用
});
</script>

<style scoped>
.file-uploader {
    padding: 20px;
}

.upload-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 2px dashed #ddd;
    margin-bottom: 20px;
}

.template-download {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}

.download-btn {
    font-size: 13px;
    background-color: #1677ff;
}

.upload-list {
    margin-top: 20px;
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.header-actions {
    display: flex;
    gap: 8px;
    align-items: center;
}

.list-header h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.file-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.file-table th,
.file-table td {
    padding: 12px 10px;
    border-bottom: 1px solid #f0f2f5;
    vertical-align: middle;
    font-size: 13px;
}

.file-table th {
    background-color: #fafafa;
    font-weight: 600;
    color: #606266;
    text-align: left;
}

.th-info,
.td-info {
    /* 自动填充剩余空间 */
}

.th-status,
.td-status {
    width: 100px;
    text-align: center;
}

.th-actions,
.td-actions {
    width: 60px;
    text-align: center;
}

.td-info {
    line-height: 1.5;
}

.file-name {
    font-size: 14px;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
    margin-bottom: 4px;
}

.file-meta {
    display: flex;
    gap: 10px;
    align-items: center;
    position: relative;
    padding-left: 24px;
}

.file-meta .serial-number {
    position: absolute;
    left: 0;
    color: #1989fa;
    font-size: 12px;
    background-color: #e8f4ff;
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid #a7d0ff;
    min-width: 20px;
    text-align: center;
}

.file-size,
.upload-time {
    font-size: 12px;
    color: #909399;
}

.action-icon {
    color: #909399;
    cursor: pointer;
    font-size: 18px;
    transition: color 0.2s ease;
}

.action-icon:hover {
    color: #f56c6c;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
   .file-uploader {
        padding: 12px;
    }

   .upload-section {
        padding: 16px;
        margin-bottom: 16px;
    }

   .upload-list {
        padding: 12px;
        margin-top: 16px;
    }

   .list-header {
        flex-direction: column;
        gap: 12px;
    }

   .header-actions {
        width: 100%;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    /* === 上传列表表格的移动端样式 === */
    .upload-list .file-table {
        display: block;
    }
    .upload-list .file-table thead {
        display: none;
    }
    .upload-list .file-table tbody {
        display: block;
    }
    .upload-list .file-table tr {
        display: block;
        padding: 16px;
        border: 1px solid #eee;
        margin-bottom: 12px;
        border-radius: 8px;
        position: relative;
    }
    .upload-list .file-table td {
        display: block;
        padding: 0;
        border: none;
    }
    .upload-list .td-info {
        width: 100%;
        padding-bottom: 32px;
    }
    .upload-list .file-name {
        font-size: 14px;
        margin-bottom: 8px;
        padding-right: 24px;
    }
    .upload-list .file-meta {
        position: absolute;
        bottom: 16px;
        left: 16px;
        padding: 0;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .upload-list .file-meta .serial-number {
        position: static;
        font-size: 12px;
        padding: 2px 6px;
        background-color: #e8f4ff;
        color: #1989fa;
        border: 1px solid #a7d0ff;
        border-radius: 4px;
    }
    .upload-list .file-size {
        font-size: 12px;
        color: #909399;
    }
    .upload-list .td-status {
        position: absolute;
        top: 16px;
        right: 16px;
        width: auto;
        padding: 0;
    }
    .upload-list .td-actions {
        position: absolute;
        /* 调整顶部位置，以防状态重叠 */
        top: 16px; 
        right: 16px;
        width: auto;
        padding: 0;
    }
    .upload-list .action-icon {
        font-size: 16px;
    }
}

.download-link {
    word-break: break-all;
    word-wrap: break-word;
    display: inline-block;
    max-width: 100%;
    color: #1677ff;
    text-decoration: none;
}

.download-link:hover {
    text-decoration: underline;
}
</style>